#ifndef TREEBUILDER_H
#define TREEBUILDER_H

#include <QObject>
#include <QStringList>
#include <QSqlDatabase>
#include <QScriptValue>
#include <QMouseEvent>

class QTreeWidget;
class QTreeWidgetItem;
class QScriptContext;


QScriptValue treeBuilderConstructor(QScriptContext *context, QScriptEngine *engine);

// Build tree from database by hierarchy codes
class SqlTreeBuilder : public QObject
{
    Q_OBJECT

    Q_PROPERTY(QString tableName READ getTableName WRITE setTableName)
    Q_PROPERTY(QString nameField READ getNameField WRITE setNameField)
    Q_PROPERTY(QString codeField READ getCodeField WRITE setCodeField)
    Q_PROPERTY(QStringList pattern READ getPattern WRITE setPattern)

public:
    SqlTreeBuilder(QTreeWidget *tree, QSqlDatabase &db);
    SqlTreeBuilder(QSqlDatabase &db, QTreeWidget *tree, const QString &tableName, const QString &nameField, const QString &codeField, const QStringList &pattern);
    ~SqlTreeBuilder();



    QString getTableName() { return m_tableName; }
    void setTableName(const QString &name) { m_tableName = name; }

    QString getNameField() { return m_nameField; }
    void setNameField(const QString &nameField) { m_nameField = nameField; }

    QString getCodeField() { return m_codeField; }
    void setCodeField(const QString &codeField) { m_codeField = codeField; }

    QStringList getPattern() { return m_pattern; }
    void setPattern(const QStringList &pattern) { m_pattern = pattern; }

public slots:
    void build();


private:
    void recursion(int level = 0, QTreeWidgetItem *parent = 0);

private:
    QString m_tableName;
    QString m_nameField;
    QString m_codeField;
    QStringList m_pattern;
    QSqlDatabase m_db;
    QTreeWidget* m_treeWidget;
    QSqlQuery *m_query;
};

#endif // TREEBUILDER_H
